package cn.hdu.liang.ch02.classpath;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 众多的Entry组成 Entry list;
 * 构造函数把参数（路径列表）按分隔符分成小路径，然后把每个小路径都转换成具体的 Entry实例
 */
public class CompositeEntry extends Entry {
    List<Entry> compositeEntries;
    String pathList;

    public CompositeEntry() {
    }

    public CompositeEntry(String pathList, String pathListSeparator) {
        // a.jar:b.jar:c.jar --> List<Entry>
        this.pathList = pathList;
        this.compositeEntries = Arrays.stream(pathList.split(pathListSeparator))
                .map(DirEntry::new).collect(Collectors.toList());
    }

    @Override
    public byte[] readClass(String className) {
        for(Entry compositeEntry : compositeEntries) {
            try {
                byte[] data = compositeEntry.readClass(className);
                if(data != null) {
                    return data;
                }
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public String className() {
        return pathList;
    }
}
